#include "page/gallery.h"

pthread_t galleryTID;
volatile bool isGalleryTIDFinished = false;

uint8_t imageIndex = 1;
uint8_t imageCount = 4;
char buf[20];

void ShowImage(BMPShowMode mode) {
    sprintf(buf, "./res/%d.bmp", imageIndex);
    Screen_ShowBMPWithModeByFile(buf, mode);
    Screen_ShowBMPByFile("./res/back.bmp", 20, 20);
}

void* DoInBackgroud(void* arg) {
    while (true) {
        TouchEvent event = Touch_GetXY();

        switch (event.gesture) {
            case LTR:
                if (imageIndex == 1) {
                    goto THREAD_END;
                } else {
                    imageIndex--;
                    ShowImage(LEFT_IN);
                }
                break;

            case RTL:
                if (imageIndex != imageCount) {
                    imageIndex++;
                    ShowImage(RIGHT_IN);
                }
                break;

            case TTB:
                if (imageIndex == 1) {
                    goto THREAD_END;
                } else {
                    imageIndex--;
                    ShowImage(TOP_IN);
                }
                break;

            case BTT:
                if (imageIndex != imageCount) {
                    imageIndex++;
                    ShowImage(BOTTOM_IN);
                }
                break;

            case CLICK: {
                uint16_t x = event.start.x;
                uint16_t y = event.start.y;
                if (x >= 20 && x < 20 + 80 && y >= 20 && y < 20 + 50) {
                    goto THREAD_END;
                }

                break;
            }
        }
    }

    return NULL;

THREAD_END:
    printf("Gallery hiding...\n");
    Gallery_Free();
    nextPage = HOME;
    return NULL;
}

void Gallery_Show() {
    printf("Gallery showing...\n");

    ShowImage(LEFT_IN);
    pthread_create(&galleryTID, NULL, DoInBackgroud, NULL);
    isGalleryTIDFinished = false;
    pthread_join(galleryTID, NULL);
}

void Gallery_Free() {
    if (isGalleryTIDFinished) {
        return;
    } else if (galleryTID == 0) {
        return;
    }

    isGalleryTIDFinished = true;
    pthread_cancel(galleryTID);
}
